//
//  ANHTMLController.m
//  WeiYiMei
//
//  Created by iMac on 2019/4/25.
//  Copyright © 2019年 liyefu. All rights reserved.
//

#import "ANHTMLController.h"
#import <WebKit/WebKit.h>

#define kNaviTitleLoading       @"正在加载…"

@interface ANHTMLController ()<WKNavigationDelegate, WKUIDelegate>

@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, copy) NSString *urlString;
@property (nonatomic, copy, nullable) NSString *titleName;
@property (nonatomic, weak) UIProgressView *progressView;

@end

@implementation ANHTMLController

- (void)dealloc
{
    [self removeKVO];
}

- (instancetype)initWithUrlString:(NSString *)urlString
                        titleName:(nullable NSString *)titleName
{
    self = [super init];
    if (self) {
        _urlString = [urlString copy];
        _titleName = [titleName copy];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self setUpWebView];
    [self loadRequest];
    [self setUpProgressView];
    [self addKVO];
}

- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    self.webView.frame = self.view.bounds;
}

- (void)setUpWebView
{
    self.title = self.titleName.length ? self.titleName : kNaviTitleLoading;
    
    WKWebViewConfiguration* webConfiguration = [[WKWebViewConfiguration alloc] init];
    WKUserContentController* contentController = [[WKUserContentController alloc] init];
    NSString *session = UserUtils.shared.session;
    WKUserScript * cookieScript = [[WKUserScript alloc] initWithSource:[NSString stringWithFormat:@"document.cookie ='JSESSIONID=%@';document.cookie = 'TeskWKCookieKey2=TeskWKCookieValue2';",session] injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
    [contentController addUserScript:cookieScript];
    webConfiguration.userContentController = contentController;
    WKPreferences *preferences = [WKPreferences new];
    webConfiguration.preferences = preferences;
    
    
    
    self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:webConfiguration];
    [self.view addSubview:self.webView];
    
    self.webView.navigationDelegate = self;
    self.webView.UIDelegate = self;
    self.webView.allowsBackForwardNavigationGestures = YES;
    if (@available(iOS 11.0, *)) {
        self.webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
}

- (void)loadRequest
{
  
//    NSString *urlStr = [NSString stringWithFormat:@"%@&JSESSIONID=%@",self.urlString,UserUtils.shared.session];
    NSURL *url = [NSURL URLWithString:self.urlString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20];
    [request setHTTPShouldHandleCookies:YES];
    [request setValue:[NSString stringWithFormat:@"JSESSIONID=%@",UserUtils.shared.session] forHTTPHeaderField:@"Cookie"];
    [self.webView loadRequest:request];
}

- (void)setUpProgressView
{
    UIProgressView *progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 2)];
    [self.view addSubview:progressView];
    self.progressView = progressView;
    self.progressView.tintColor = kColorFF2C2C;
    self.progressView.trackTintColor = [UIColor clearColor];
}

- (void)addKVO
{
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
}

- (void)removeKVO
{
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        NSLog(@"estimatedProgress %f",self.webView.estimatedProgress);
        CGFloat progress = self.webView.estimatedProgress;
        [self.progressView setProgress:progress animated:YES];
        if (progress >= 1.0f) { // 加载完成0.3秒后，进度条消失
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.progressView.progress = 0;
            });
            
            [self.webView evaluateJavaScript:@"document.title" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
                NSString *title = [(NSString *)result stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
                self.title = title; // 加载完成时的标题
            }];
            
        } else {
            self.title = kNaviTitleLoading; // 加载中的标题
        }
    }
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler
{
    NSHTTPURLResponse *response = (NSHTTPURLResponse *)navigationResponse.response;
    NSArray *cookies =[NSHTTPCookie cookiesWithResponseHeaderFields:[response allHeaderFields] forURL:response.URL];
    //读取wkwebview中的cookie 方法1
    for (NSHTTPCookie *cookie in cookies) {
        [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
    }
    
    decisionHandler(WKNavigationResponsePolicyAllow);
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation
{
    
}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error
{
    
}

- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error
{
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
